﻿using SHDM.Cache;
using SHDM.Web.DataAccess;
using SHDM.Web.Infrastructure;
using SHDM.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SHDM.Web.Controllers
{
    [Authenticator]
    [RoutePrefix("api/Account")]
    public class AccountController : ApiBaseController
    {
        /// <summary>
        /// 登录
        /// </summary>
        /// <param>
        /// LoginName:账号
        /// Password:密码
        /// </param>
        /// <returns></returns>
        [OverrideAuthentication]
        [AllowAnonymous]
        [Route("Login")]
        [HttpPost]
        public Result Login(LoginModel model)
        {
            if(string.IsNullOrEmpty(model.LoginName) || string.IsNullOrEmpty(model.Password))
            {
                return new Result() { ErrorCode=1, ErrorMessage="请输入账号和密码" };
            }
            var u = new DataAccess.SHDMEntities().sh_users.FirstOrDefault(e => e.LoginName == model.LoginName);
            if(u == null)
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "账号密码错误" };
            }

            var encryptPassword = TextUtil.MD5Encrypt(model.Password);
            if(string.Compare(encryptPassword,u.Password,true) != 0)
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "账号密码错误" };
            }
            string token = System.Guid.NewGuid().ToString();
            var ac = new AccountInfo() { LoginName = u.LoginName, Role = u.Role, ID = u.ID, DeptID = u.DeptID,Token=token };
            Cacher.Instance.Set($"{Cacher.KeySpace.UserToken}.{token}", ac, 120);
            return new Result() { Data= ac, ErrorMessage="登录成功" };
        }

        [Route("GetUserInfo")]
        [HttpGet]
        public Result GetUserInfo()
        {
            return new Result() { Data=this.AccountInfo };
        }

        [Route("ChangePW")]
        [HttpGet]
        public Result ChangePW(string pw,string oldpw)
        {
            if (string.IsNullOrEmpty(pw) || string.IsNullOrEmpty(oldpw))
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "请输入密码" };
            }
            var db = new SHDMEntities();
            var u = db.sh_users.FirstOrDefault(e => e.ID == this.AccountInfo.ID);
            if(u == null)
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "账号不存在???" };
            }
            if(string.Compare(u.Password,TextUtil.MD5Encrypt(oldpw)) != 0)
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "旧密码错误" };
            }
            u.Password = TextUtil.MD5Encrypt(pw);
            db.SaveChanges();
            return new Result() { ErrorMessage = "操作成功" };
        }      
    }
    
}
